package com.cn.jdia.springmvc.handlers;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.gson.Gson;

@Controller
public class LoginController {

	@RequestMapping("/login")
	public String login(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();

		String name = request.getParameter("name");
		String pass = request.getParameter("pass");

		System.out.println(name);
		System.out.println(pass);

		@SuppressWarnings("resource")
		ClassPathXmlApplicationContext w_context = new ClassPathXmlApplicationContext("springmvc.xml");
		DataSource ds = (DataSource) w_context.getBean("dataSource");

		Map<String, String> map = new HashMap<>();
		try {
			Connection conn = ds.getConnection();
			Statement st = conn.createStatement();

			StringBuffer sb = new StringBuffer("select user_id,name_ch,authority from jan_user where user_name='")
					.append(name).append("' and password='").append(pass).append("'");
			ResultSet rs = st.executeQuery(sb.toString());
			int count = 0;

			int user_id = -1;
			String name_ch = "";
			String authority = "";
			while (rs.next()) {
				user_id = rs.getInt("user_id");
				name_ch = rs.getString("name_ch");
				authority = rs.getString("authority");
				count++;
			}

			if (count == 0) {
				System.out.println("no this user");
			}
			System.out.println("id:" + user_id);
			System.out.println("nc:" + name_ch);
			System.out.println("au:" + authority);

			map.put("id", Integer.toString(user_id));
			map.put("nc", name_ch);
			map.put("au", authority);

			if (user_id != -1) {
				String encode = URLEncoder.encode(name_ch, "UTF-8");
				Cookie username_cookie = new Cookie("name_ch", encode);
				
				String idencode=URLEncoder.encode(user_id+"", "UTF-8");
				Cookie userid_cookie = new Cookie("user_id", idencode);
				
				String auencode=URLEncoder.encode(authority+"", "UTF-8");
				Cookie au_cookie = new Cookie("user_au", auencode);
				
				username_cookie.setMaxAge(1200);
				userid_cookie.setMaxAge(1200);
				au_cookie.setMaxAge(1200);
				
				response.addCookie(username_cookie);
				response.addCookie(userid_cookie);
				response.addCookie(au_cookie);
			}

			st.close();
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		Gson gson = new Gson();
		String json = gson.toJson(map);

		out.write(json);
		out.flush();
		out.close();

		return null;
	}

}
